#
# A very simple datazoomer calculator
#


import dzpage, dzutil, dzentity, zoom


calc_keypad = """
<span style="font-size:40px;">%(value).4f</span>

[-C-]
[-7-] [-8-] [-9-] [-*-]
[-4-] [-5-] [-6-] [-/-]
[-1-] [-2-] [-3-] [-+-]
[-0-] [-.-] [-=-] [---]
"""

import dzentity
class Registers(dzentity.Entity):
    def __init__(self):
        self.value = self.pos = self.dec = self.reg = 0
        self.op = ''

class Calculator:
    def render(self):
        value = zoom.zoomer.session.calculator_value or 0

        page = dzpage.Page()
        page.title = 'Calculator'
        page.content = dzutil.render(calc_keypad % dict(value=value),form=1,action='click',con='calculator')
        return page.render()

    def _click(self,**args):

        key   = args.values()[0]

        value = zoom.zoomer.session.calculator_value or 0
        pos   = zoom.zoomer.session.calculator_pos or 1
        op    = zoom.zoomer.session.calculator_op or ''
        dec   = zoom.zoomer.session.calculator_dec or 0
        reg   = zoom.zoomer.session.calculator_reg or 0

        if key in ['+','-','*','/','='] and op:
            if op == '+': value = reg + value
            if op == '-': value = reg - value
            if op == '*': value = reg * value
            if op == '/': value = float(reg) / value
            op = ''

        if key in ['0','1','2','3','4','5','6','7','8','9','0']:
            if dec:
                value = value + (value / dec**10)
                dec += 1
            else:
                value = (value * 10) + int(key)

        elif key == '.':
            dec = 1

        elif key == 'C':
            value = dec = reg = 0
            op    = ''

        elif key in ['+','-','*','/']:
            op = key
            reg = value
            value = 0

        zoom.zoomer.session.calculator_value = value
        zoom.zoomer.session.calculator_pos   = pos
        zoom.zoomer.session.calculator_op    = op
        zoom.zoomer.session.calculator_dec   = dec
        zoom.zoomer.session.calculator_reg   = reg
        
result = Calculator()



